<!DOCTYPE html>
<html>
<head>
</head>
<body>
<project-model></project-model>
<url-history-model></url-history-model>
<websocket-url-history-model></websocket-url-history-model>
<history-data-model></history-data-model>
<client-certificate-model></client-certificate-model>
<variables-model></variables-model>
<auth-data-model></auth-data-model>
<request-model></request-model>
<host-rules-model></host-rules-model>
<rest-api-model></rest-api-model>
<url-indexer></url-indexer>
<script type="module">
  /* eslint-disable import/no-extraneous-dependencies */
  /* eslint-disable no-console */
  import PouchDB from '../../../web_modules/pouchdb/dist/pouchdb.js';
  import PouchQuickSearch from '../../../web_modules/@advanced-rest-client/pouchdb-quick-search/dist/pouchdb.quick-search.min.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/project-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/url-history-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/websocket-url-history-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/history-data-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/client-certificate-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/variables-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/auth-data-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/request-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/host-rules-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/rest-api-model.js';
  import '../../../web_modules/@advanced-rest-client/arc-models/url-indexer.js';
  import { ImportFactory } from '../../../web_modules/@advanced-rest-client/arc-models/index.js';

  const { ipcRenderer } = require('electron');
  const fs = require('fs-extra');

  window.PouchDB = PouchDB;
  window.PouchQuickSearch = PouchQuickSearch;
  window.PouchDB.plugin(window.PouchQuickSearch);

  ipcRenderer.send('data-transport-ready', 'receiver');
  
  async function importData(file) {
    const exists = await fs.pathExists(file);
    if (!exists) {
      ipcRenderer.send('data-importer-finished');
      return;
    }
    try {
      const data = await fs.readJson(file);
      const factory = new ImportFactory();
      const errors = await factory.importData(data);
      if (errors) {
        console.error(errors);
      }
    } catch (e) {
      ipcRenderer.send('db-error', e.message, e.stack);
      return;
    }
    try {
      const indexer = document.querySelector('url-indexer');
      await indexer.reindex('saved');
      await indexer.reindex('history');
    } catch(e) {
      console.error(e);
    }
    ipcRenderer.send('data-importer-finished');
  }
  ipcRenderer.on('receiver-start', (e, exportFile) => importData(exportFile));
</script>
</body>
</html>
